﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Collections;
using System.Diagnostics;

namespace NetStatistics
{
	[Serializable]
	public class NetSpeedMonitor
	{
		public NetSpeedMonitor()
		{
			this.adapters = new List<NetworkAdapter>();			

			GetAdapters();

			refreshTimer = new Timer(1000);
			refreshTimer.Elapsed += new ElapsedEventHandler(refreshTimer_Elapsed);			
		}

		private Timer refreshTimer;
		
		private List<NetworkAdapter> adapters;
		public NetworkAdapter[] Adapters
		{
			get { return adapters.ToArray(); }			
		}		

		private void GetAdapters()
		{
			PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");

			foreach (string adapterName in category.GetInstanceNames())
			{
				if (adapterName.Equals("MS TCP Loopback Interface", StringComparison.InvariantCultureIgnoreCase))
					continue;

				NetworkAdapter adapter = new NetworkAdapter(adapterName);
				adapter.DownloadedBytesCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", adapterName);
				adapter.UploadedBytesCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", adapterName);

				this.adapters.Add(adapter);
			}
		}

		public void StartSpeedMonitoring()
		{
			foreach (NetworkAdapter adapter in this.adapters)
				adapter.Init();

			refreshTimer.Enabled = true;
		}

		public void StopSpeedMonitoring()
		{
			refreshTimer.Enabled = false;
		}

		private void refreshTimer_Elapsed(object sender, ElapsedEventArgs e)
		{
			foreach (NetworkAdapter adapter in this.Adapters)
				adapter.Refresh();
		}
	}
}
